package com.levi.rabbitmq.task;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TaskConsumer {

    public static final String TASK_QUEUE_NAME = "task_hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置rabbitmq地址
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //建立连接
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();

        //声明队列             队列名称        是否持久化         是否独有          是否自动删除       参数
        channel.queueDeclare(TASK_QUEUE_NAME, false, false, false, null);
        System.out.println("开始接收消息");
        //实现消息公平派遣，在一个消息没有消费完之前不会接收新的消息   自动确认改为手动确认
        channel.basicQos(1);
        //接收消息                                  自动确认
        channel.basicConsume(TASK_QUEUE_NAME, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                super.handleDelivery(consumerTag, envelope, properties, body);

                String message = new String(body, "UTF-8");
                System.out.println("收到了消息: " + message);
                try {
                    doWork(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(message + "消息处理完成");
                    //在消息处理完之后进行确认                        把多个一起确认
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }

            }
        });
    }

    private static void doWork(String task) {
        System.out.println("开始处理消息");
        char[] chars = task.toCharArray();
        for (char c : chars) {
            if (c == '.') {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
